﻿/* 版本记录
 * 0000 20200902  by linson add
 * 0001 
 * */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Security;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Dao;
using GKQC.Common;
using GKQC.DbHelper.Services;
using GKQC.Language;

namespace GKQC.Forms
{
    /// <summary>
    /// 系统管理主窗口
    /// </summary>
    public partial class FormUser : Form
    {
        UserModel user = null;
        AllDbContext dbContext = null;
        public UserModel currentUser = new UserModel();
        List<UserModel> userList = null;
        FormStatus formStatus = FormStatus.Browser;
        EncryptSugar encryptSugar = null;
        //readonly string s0 = "123WER7890qwertyuiopasdfghjklzxcvbn123456789012er3";

        public FormUser(UserModel user, AllDbContext dbContext)
        {
            InitializeComponent();
            try
            {
                this.dataGridView1.AutoGenerateColumns = false;
            this.user = user;
            this.tssUser.Text = user.UserName;
            this.dbContext = dbContext;
            encryptSugar = EncryptSugar.GetInstance();

            
                BindingUserGroup();
                BindingData();
                if(userList != null && userList.Count > 0)
                    currentUser = userList[0];
                else
                    currentUser = new UserModel();

                BindingControls();
                SetControlsEnable();
                LanguageHelper.SetControlLanguageText(this);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message);
                Logger.LogError(ex);
            }
        }

        void BindingUserGroup()
        {
            try
            {
                var usergroups = dbContext.QcDb.Queryable<UserGroupModel>().Where(g => g.IsUse).ToList();
                cboUserGroup.DisplayMember = "GroupName";
                cboUserGroup.ValueMember = "GroupCode";
                cboUserGroup.DataSource = new BindingList<UserGroupModel>(usergroups);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }


        private void Fmain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Application.Exit();
        }

        private void FormUser_Resize(object sender, EventArgs e)
        {

        }

        private void tsmAdd_Click(object sender, EventArgs e)
        {
            formStatus = FormStatus.Add;
            txtUserCode.Text = string.Empty;
            ClearControl();
            currentUser.Password = "123456";
            SetControlsEnable();       
        }

        void ClearControl()
        {
            currentUser = new UserModel();
            BindingControls();
        }

        bool ValidtingControl()
        {
            bool flag = true;
            string msg = "提示";
            if (string.IsNullOrWhiteSpace(txtUserCode.Text))
            {
                QMessageBox.Show("请输入：" + lblUserCode.Text, msg, MessageBoxButtons.OK, MessageBoxIcon.Information);
                flag = false;
                txtUserCode.Focus();
            }
            else if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                QMessageBox.Show("请输入：" + lblUserName.Text, msg, MessageBoxButtons.OK, MessageBoxIcon.Information);
                flag = false;
                txtUserName.Focus();
            }
            else if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                QMessageBox.Show("请输入：" + lblPassword.Text, msg, MessageBoxButtons.OK, MessageBoxIcon.Information);
                flag = false;
                txtPassword.Focus();
            }

            return flag;
        }

        private void FormUser_Load(object sender, EventArgs e)
        {

        }

        void BindingControls()
        {
            this.txtUserCode.DataBindings.Clear();
            this.txtUserCode.DataBindings.Add("Text", currentUser, "UserCode");
            this.txtPassword.DataBindings.Clear();
            this.txtPassword.DataBindings.Add("Text", currentUser, "Password");
            this.txtEmail.DataBindings.Clear();
            this.txtEmail.DataBindings.Add("Text", currentUser, "Email");
            this.txtUserName.DataBindings.Clear();
            this.txtUserName.DataBindings.Add("Text", currentUser, "UserName");
            this.txtDept.DataBindings.Clear();
            this.txtDept.DataBindings.Add("Text", currentUser, "Dept");
            this.chkIsAdmin.DataBindings.Clear();
            this.chkIsAdmin.DataBindings.Add("Checked", currentUser, "IsAdmin");
            this.chkIsUse.DataBindings.Clear();
            this.chkIsUse.DataBindings.Add("Checked", currentUser, "IsUse");
            this.cboUserGroup.DataBindings.Clear();
            this.cboUserGroup.DataBindings.Add("SelectedValue", currentUser, "GroupCode");
        }

        private void tsmSave_Click(object sender, EventArgs e)
        {
            try
            {
                
                if (currentUser == null) return;
                if (!this.Validate()) return;

                this.Cursor = Cursors.WaitCursor;
                
                if (!ValidtingControl()) return;

                if (currentUser.Password.Length < 50)
                {
                    currentUser.Password = encryptSugar.Encrypto(currentUser.Password) + RandomSugar.GetRandWord(50);
                }
                if(string.IsNullOrEmpty(cboUserGroup.SelectedText))
                {
                    currentUser.GroupCode = null;
                }

                if (formStatus == FormStatus.Add)
                {
                    int i = dbContext.QcDb.Insertable<UserModel>(currentUser).ExecuteCommand();
                    if (i > 0)
                    {
                        Log(tsmAdd);
                        BindingData();
                    }
                }
                else if (formStatus == FormStatus.Edit)
                {
                    dbContext.QcDb.Updateable(currentUser).ExecuteCommand();
                    Log(tsmEdit);
                }

                formStatus = FormStatus.Browser;
                //BindingData();
                SetControlsEnable();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0003", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            if(currentUser == null)
            {
                QMessageBox.Show("請選擇要編輯的用戶!","提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            formStatus = FormStatus.Edit;
            SetControlsEnable();
        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (currentUser == null)
                {
                    QMessageBox.Show("請選擇要刪除的用戶", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (currentUser.UserCode.ToLower() == "admin")
                {
                    QMessageBox.Show("不能刪除Admin用戶", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (QMessageBox.Show("即將刪除用戶：" + txtUserCode.Text, "請確認",MessageBoxButtons.OKCancel,MessageBoxIcon.Question)
                    == DialogResult.Cancel)
                {
                    return;
                }

                dbContext.QcDb.Deleteable<UserModel>(currentUser).ExecuteCommand();
                Log(tsmDelete);
                QMessageBox.Show("刪除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                BindingData();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0004", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmCancel_Click(object sender, EventArgs e)
        {
            formStatus = FormStatus.Browser;
            SetControlsEnable();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(dataGridView1.CurrentRow != null)
            {
                currentUser = dataGridView1.CurrentRow.DataBoundItem as UserModel;
                BindingControls();
            }
            else
            {
                ClearControl();
            }
        }

        void SetControlsEnable()
        {
            if(formStatus == FormStatus.Browser)
            {
                txtUserCode.ReadOnly = true;
                txtUserName.ReadOnly = true;
                txtPassword.ReadOnly = true;
                txtEmail.ReadOnly = true;
                chkIsAdmin.Enabled = false;
                chkIsUse.Enabled = false;
                txtDept.ReadOnly = true;
                dataGridView1.Enabled = true;
                cboUserGroup.Enabled = false;


                tsmAdd.Enabled = true;
                tsmEdit.Enabled = true;
                tsmDelete.Enabled = true;
                tsmSave.Enabled = false;
                tsmCancel.Enabled = false;
                tsmExit.Enabled = true;
            }
            else
            {
                txtUserCode.ReadOnly = false;
                txtUserName.ReadOnly = false;
                txtPassword.ReadOnly = false;
                txtEmail.ReadOnly = false;
                txtDept.ReadOnly = false;
                chkIsAdmin.Enabled = true;
                chkIsUse.Enabled = true;
                dataGridView1.Enabled = false;
                cboUserGroup.Enabled = true;

                tsmAdd.Enabled = false;
                tsmEdit.Enabled = false;
                tsmDelete.Enabled = false;
                tsmSave.Enabled = true;
                tsmCancel.Enabled = true;
                tsmExit.Enabled = false;
            }

            if (formStatus == FormStatus.Edit) txtUserCode.ReadOnly = true;
            if (txtUserCode.Text == "Admin" && chkIsAdmin.Checked) chkIsAdmin.Enabled = false;
            if (txtUserCode.Text == "Admin" && chkIsUse.Checked) chkIsUse.Enabled = false;
            if (txtUserCode.Text == "Admin") cboUserGroup.Enabled = false;
        }

        void BindingData()
        {
            userList = dbContext.QcDb.Queryable<UserModel>().ToList();
            dataGridView1.DataSource = userList;
            if (userList != null && userList.Count > 0)
            {
                currentUser = userList[0];
                tssCount.Text = userList.Count.ToString();
            }
            else
            {
                ClearControl();
                tssCount.Text = "0";
            }

            BindingControls();
        }

        void Log(ToolStripMenuItem item)
        {
            try
            {
                SysLogService.Log(dbContext, user, this, item.Text, txtUserCode.Text, string.Empty);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }
    }
}
